package lk.icta.common.web.converter;

import org.apache.struts2.util.StrutsTypeConverter;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Map;

public class ELandDateConverter extends StrutsTypeConverter {
    private final DateFormat utcDfm = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
    private final DateFormat ISO8601Format = new SimpleDateFormat("yyyy-MM-dd");

    @Override
    public Object convertFromString(Map context, String[] values, Class toClass) {
        if (values.length == 0 || values[0] == null || values[0].trim().equals("")) {
            return null;
        }
        return getDateFromISO8601String(values[0]);
    }

    @Override
    public String convertToString(Map context, Object o) {
        if (o instanceof Date) {
            return getISO8601FormattedString((Date) o);
        }
        return "";
    }

    /**
     * Returns an ISO8601 comliant (W3C standard as well) date. yyyy-MM-dd
     *
     * @param date A java.util.Date object
     * @return the formatted String
     */
    public String getISO8601FormattedString(Date date) {
        synchronized (ISO8601Format) {
            return ISO8601Format.format(date);
        }
    }

    /**
     * Returns a java.util.Date from an ISO8601 compliant date string yyyy-MM-dd
     * returns null if the string is not parseable.
     *
     * @param s String formatted in yyyy-MM-dd
     * @return date
     */
    public Date getDateFromISO8601String(String s) {
        try {
            synchronized (ISO8601Format) {
                return ISO8601Format.parse(s);
            }
        } catch (ParseException e) {
            return null;
        }
    }
}
